import { PlusOutlined , QuestionCircleOutlined} from '@ant-design/icons';
import { Button, Divider, message, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import UpdateModel from './components/UpdateModel';
import { VersionListItem } from './data.d';
import { versionList,versionDel, versionDisable } from './service';

const UpdateList: React.FC<{}> = () => {
  const [addModalVisible, handleModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [statusModalVisible, handleStatusModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  //添加
  const handleAdd = async (callback: string) => {
    if (callback == 'success') {
      if (actionRef.current) {
        handleModalVisible(false);
        actionRef.current.reload();
      }
    }
  };

  //删除--删除弹出框
  const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此版本将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          versionDel(id)
            .then((res) => {
              if (res.code === 200) {
                message.success('删除成功');
                handleDeleteModalVisible(false);
                actionRef.current?.reload?.();
                resolve(true);
              } else {
                message.error('删除失败，' + res.message);
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };

  const bytesToSize = (bytes:number) => {
    if (bytes === 0) return '0 B';
    let k = 1024,
      sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
      i = Math.floor(Math.log(bytes) / Math.log(k));
  
    return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  }

  //详情--弹出框
  const detailModel = (values:VersionListItem) =>{
    Modal.info({
      visible: detailModalVisible,
      title: '升级包详情',
      icon: "",
      content: (
        <>
          <span style={{display:"block",marginBottom:5}}>版本名称：{values.versionName}</span>
          <span style={{display:"block",marginBottom:5}}>文件大小：{bytesToSize(values.size)}</span>
          <span style={{display:"block"}}>版本描述：{values.description}</span>
        </>
      ),
      okText: '返回',
      onOk: () => {
        handleDetailModalVisible(false);
      },
    });
  }

  //启用停用弹出框
  const updateStateCommand = (record: VersionListItem) => {
    if (record != null && record != undefined) {
      let id = record.id;
      let status = record.status;
      let title = "";
      if(status){
        title = "禁用";
      }else{
        title = "启用";
      }
      Modal.confirm({
        visible: statusModalVisible,
        title: '是否'+title,
        icon: <QuestionCircleOutlined />,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return new Promise((resolve, reject) => {
            versionDisable(id)
              .then((res) => {
                if (res.code === 200) {
                  message.success(title+'成功');
                  handleStatusModalVisible(false);
                  actionRef.current?.reload?.();
                  resolve(true);
                } else {
                  message.error(title+'失败,'+res.message);
                  resolve(false);
                }
              })
              .catch((error) => {
                message.error(title+'失败');
                reject(error);
              });
          });
        },
      });
    }
  };

  const columns: ProColumns<VersionListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '版本号',
      dataIndex: 'versionNo',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '版本名',
      dataIndex: 'versionName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'text',
      hideInSearch: true,
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '包类型',
      dataIndex: 'type',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateDatetime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            href={record.storeId} target="_blank"
          >
            下载
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              detailModel(record);
            }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <a style={{color:record.status ? "#ff4d4f" : "#1890ff"}}
            onClick={() => {
              updateStateCommand(record);
            }}
          >
            {record.status ? "禁用" : "启用"}
          </a>
          <Divider type="vertical" />
          <a 
           onClick={() => {
              delConfirm(record.id);
            }}
          >删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<VersionListItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={false}
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }} //默认每页显示10条
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建版本
          </Button>
        ]}
        request={(params, sorter, filter) => versionList({ ...params, sorter, filter })}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        // }}
      />
      <UpdateModel onSubmit={handleAdd} onCancel={() => handleModalVisible(false)} modalVisible={addModalVisible}>
        <ProTable<VersionListItem, VersionListItem>/>
      </UpdateModel>
    </PageContainer>
  );
};

export default UpdateList;
